from faker import Faker
import random
from datetime import datetime, timedelta
from data_mock.utils import MysqlUtils_AI

fake = Faker('zh_CN')


# ========== 药品相关配置 ==========
GENERIC_NAMES = ['多柔比星', '顺铂', '紫杉醇', '奥沙利铂', '环磷酰胺']
FORMS = ['片剂', '注射液', '胶囊剂', '颗粒剂']
HOSPITALS = [
    {'code': 'HOSP001', 'name': '协和医院'},
    {'code': 'HOSP002', 'name': '华西医院'},
    {'code': 'HOSP003', 'name': '第一人民医院'},
    {'code': 'HOSP004', 'name': '省肿瘤医院'}
]
MANUFACTURES = ['上海罗氏制药有限公司', '江苏恒瑞医药股份有限公司', '齐鲁制药有限公司']
PACK_UNITS = ['盒', '瓶', '支']
PRES_ORIGINS = ['门诊', '住院', '急诊']


# ========== 生成函数 ==========
def generate_b01_2_records(num_records=100):
    sql_statements = []

    for i in range(num_records):
        hospital = random.choice(HOSPITALS)
        pres_quantity = round(random.uniform(0.1, 50), 4)
        pres_unit_price = round(random.uniform(10, 200), 4)
        pres_total_price = round(pres_quantity * pres_unit_price, 4)
        pres_date = fake.date_time_between(start_date='-1y', end_date='now')
        record_datetime = fake.date_time_between(start_date=pres_date, end_date='now')

        data = {
            'approval_no': f"国药准字H{random.randint(100000,999999)}",
            'form': random.choice(FORMS),
            'from_table': random.choice([None, 't_drug_usage', 't_inventory']),
            'from_yy_record_id': fake.uuid4()[:8],
            'generic_name': random.choice(GENERIC_NAMES),
            'hos_drug_code': f"HOS{random.randint(10000,99999)}",
            'hospital_code': hospital['code'],
            'hospital_name': hospital['name'],
            'insurance_type': random.choice(['医保', '自费', '新农合']),
            'manufac': random.choice(MANUFACTURES),
            'packing_quantity': str(random.randint(1, 100)),
            'packing_unit': random.choice(PACK_UNITS),
            'pres_date': pres_date.strftime('%Y-%m-%d %H:%M:%S'),
            'pres_origin': random.choice(PRES_ORIGINS),
            'pres_quantity': pres_quantity,
            'pres_sn': f"PRES{100000+i}",
            'pres_total_price': pres_total_price,
            'pres_unit_price': pres_unit_price,
            'record_datetime': record_datetime.strftime('%Y-%m-%d %H:%M:%S'),
            'spec': f"{random.randint(10,500)}mg",
            'trade_name': f"{random.choice(GENERIC_NAMES)}胶囊",
            'yy_collection_datetime': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'yy_record_md5': fake.md5(),
            'yy_upload_status': 0,
            'yy_etl_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'yy_batch_time': datetime.now().strftime('%Y%m%d'),
            'yy_record_batch_id': f"BATCH{datetime.now().strftime('%Y%m%d')}_{i}",
            'branch_code': f"BR{random.randint(1,10):02d}",
            'branch_name': f"{hospital['name']}分院"
        }

        sql = generate_sql('b01_2', data)
        sql_statements.append(sql)

    return sql_statements


# ========== 生成 SQL ==========
def generate_sql(table, data):
    columns = []
    values = []
    for k, v in data.items():
        columns.append(f"`{k}`")
        if v is None:
            values.append("NULL")
        elif isinstance(v, (int, float)):
            values.append(str(v))
        else:
            escaped_value = str(v).replace("'", "''")
            values.append(f"'{escaped_value}'")
    return f"INSERT INTO `{table}` ({', '.join(columns)}) VALUES ({', '.join(values)});"


# ========== 执行生成 ==========
if __name__ == "__main__":
    print("开始生成 b01_2 药品使用数据...")
    records = generate_b01_2_records(50)  # 生成 50 条测试数据
    # 写入数据库
    MysqlUtils_AI.insert_data_to_hub(records, 'b01_2')
